<?php

namespace Hilaoyu\LaravelExtend\Services\Files\Middleware;

use Closure;
use Hilaoyu\LaravelPrivateApi\PrivateApiDeDataMiddlewareAbstract;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Http\Request;


class FilesPrivateApiServiceDeDataMiddleware extends PrivateApiDeDataMiddlewareAbstract
{
    protected function checkAuthApp(Request $request){

        if(!$request->route()->hasParameter('_auth_app')){
            $app_id = $request->input('app_id','');
            $app = null;
            if($app_id){
                $app = UtilSupport::tryQuiet(function () use ($app_id){
                    $model = UtilSupport::makeClass(config('file_service.service_authorize_model'));
                    return $model->find($app_id);
                });
            }

            if('1' != data_get($app,'status')){
                $app =  null;
            }

            $request->route()->setParameter('_auth_app',$app);
        }
        
        return $request->route('_auth_app');
    }
    protected function getEncryptSecret(Request $request): string
    {
        if($app = $this->checkAuthApp($request)){
            return $app->secret;
        }
        return '';
    }

    public function handle(Request $request, Closure $next)
    {
        if(! $app = $this->checkAuthApp($request)){
            return comResponse()->failed('应用未授权')->json();
        }

        return parent::handle($request, $next); // TODO: Change the autogenerated stub
    }
}
